<script setup lang="ts">
import { computed, ref } from 'vue'
import { getAllOrdersApi } from '@/services/orderApi'
import { onLoad, onShow, onHide } from '@dcloudio/uni-app'
import type { order_list_type } from '@/types/order'
import { BaseUrl } from '@/utils/request'
import { formatDate } from '@/utils/formatDate'
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const params = defineProps<{ type: number }>()
const pages = ref(0)
const size = ref(4)
// 当前页存储的type
const localType = ref(params.type)
// index用于判断当前的分类，防止用户重复点击
const index = ref(0)
const count = ref(1) // 总页数
const totalPages = computed(() => {
  return Math.ceil(count.value / size.value)
})
const order_state = ref(0)

// tabs 数据
const orderTabs = ref([
  { orderState: 0, title: '全部' },
  { orderState: 1, title: '待付款' },
  { orderState: 2, title: '待发货' },
  { orderState: 3, title: '待收货' },
  { orderState: 4, title: '待评价' },
])
const order_list = ref<order_list_type[]>([] as order_list_type[])
const without_repetition = computed(() => {
  // 使用Map根据订单号去重，创建一个map对象
  const seen = new Map()
  return order_list.value.filter((item) => {
    // 检查当前订单号是否存在于Map中
    // Map的查找操作时间复杂度为O(1)，性能高效
    const exists = seen.has(item.order_number)
    // 创建空Map用于存储已处理的订单号
    // true值没有特殊含义，仅作为占位符存在
    seen.set(item.order_number, true)
    return !exists
  })
})
const getAllOrders = async () => {
  pages.value++
  if (totalPages.value >= pages.value) {
    const res = await getAllOrdersApi(localType.value!, pages.value)
    count.value = res.count!
    order_list.value.push(...res.data!)
  } else {
    uni.showToast({
      title: '没有更多数据了',
      icon: 'none',
    })
  }
}

onLoad(async () => {
  await getAllOrders()
})
// 获取template需要显示的总数量
const get_number = (item: order_list_type) => {
  let num = item.num
  if (item.son_orders) {
    item.son_orders.forEach((element) => {
      num += element.num
    })
  }
  return num
}
// // 获取template需要显示的总价格
const get_price = (item: order_list_type) => {
  let price = item.num * (item.actual_payment * 100)
  if (item.son_orders) {
    item.son_orders.forEach((el) => {
      price += el.num * (el.actual_payment * 100)
    })
  }
  return price / 100
}
const navigateToPay = (order_number: string) => {
  uni.navigateTo({
    url: `/pages/order/components/orderDetail?order_number=${order_number}`,
  })
}
const changeOrderState = async (item_index: number) => {
  if (localType.value === item_index) {
    return
  }
  localType.value = item_index
  pages.value = 1
  order_list.value = []
  if (totalPages.value >= pages.value) {
    const res = await getAllOrdersApi(localType.value, pages.value)
    count.value = res.count!
    console.log(count)
    if (!res.count) {
      // 如果没有数据的话，会影响到其他的请求，所以需要重新赋值
      count.value = 1
      console.log('没有数据')
    }
    order_list.value.push(...res.data!)
  }
}

// onShow(async () => {
//   // uni.$on是用于全局事件监听的，允许不同页面或组件之间的通信。
//   pages.value = 1
//   order_list.value = []
//   // uni.$on('refreshOrderList', getAllOrders)
// })
// 需要解释onHide的典型使用场景，比如在页面隐藏时移除事件监听器，
// 以避免内存泄漏或重复执行
// 例如，在onShow中监听事件，在onHide中移除，确保页面不可见时不再处理这些事件
// onHide(() => {
//   uni.$off('refreshOrderList', getAllOrders)
// })
// const refreshOrderList = () => {

//   getAllOrders(0)
// }
</script>

<template>
  <view class="viewport">
    <!-- tabs -->
    <view class="tabs">
      <text
        v-for="(item, i) in orderTabs"
        :key="item.orderState"
        class="titem"
        @tap="changeOrderState(i)"
      >
        {{ item.title }}
      </text>
      <!-- 游标 -->
      <view class="cursor" :style="{ left: localType * 20 + '%' }"></view>
    </view>
    <!-- 滑动容器 -->
    <swiper class="swiper" @change="changeOrderState($event.detail.current)">
      <!-- 滑动项 ,滑动切换tabs-->
      <swiper-item v-for="item in orderTabs" :key="item.orderState">
        <!-- 订单列表 -->
        <scroll-view scroll-y class="orders" @scrolltolower="getAllOrders()">
          <view class="card" v-for="item in without_repetition" :key="item.id">
            <!-- 订单信息 -->
            <view class="status">
              <text class="date">{{ formatDate(item.created_time) }}</text>
              <!-- 订单状态文字 -->
              <text>{{ orderTabs[item.order_of_payment].title }}</text>
              <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
              <text class="icon-delete"></text>
            </view>
            <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
            <navigator
              class="goods"
              :url="`/pages/order/components/orderDetail?order_number=${item.order_number}`"
              hover-class="none"
            >
              <view class="cover">
                <image mode="aspectFit" :src="BaseUrl + item.sku_info.image"></image>
              </view>
              <view class="meta">
                <view class="name ellipsis">{{ item.goods_name }}</view>
                <view class="type">
                  <view>{{ item.sku_info.sku_name_arr }}</view>
                  <view>{{ item.num }}</view>
                </view>
              </view>
            </navigator>
            <template v-if="item.son_orders">
              <navigator
                v-for="son in item.son_orders"
                :key="son.id"
                class="goods"
                :url="`/pages/order/components/orderDetail?order_number=${item.order_number}`"
                hover-class="none"
              >
                <view class="cover">
                  <image mode="aspectFit" :src="BaseUrl + son.sku_info.image"></image>
                </view>
                <view class="meta">
                  <view class="name ellipsis">{{ son.goods_name }}</view>
                  <view class="type">
                    <view>{{ son.sku_info.sku_name_arr }}</view>
                    <view>{{ son.num }}</view>
                  </view>
                </view>
              </navigator>
            </template>

            <!-- 支付信息 -->
            <view class="payment">
              <text class="quantity">共{{ get_number(item) }}件商品</text>
              <text>实付</text>
              <text class="amount"> <text class="symbol">¥</text>{{ get_price(item) }}</text>
            </view>
            <!-- 订单操作按钮 -->
            <view class="action">
              <!-- 待付款状态：显示去支付按钮 -->
              <template v-if="item.order_of_payment === 1">
                <view class="button primary" @tap="navigateToPay(item.order_number)">去支付</view>
              </template>
              <template v-else>
                <navigator
                  class="button secondary"
                  :url="`/pages/order/order?order_number=${item.order_number}`"
                  hover-class="none"
                >
                  再次购买
                </navigator>
                <!-- 待收货状态: 展示确认收货 -->
                <view v-if="item.order_of_payment === 3" class="button primary">确认收货</view>
              </template>
            </view>
          </view>
          <!-- 底部提示文字 -->
          <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
            {{ totalPages > pages ? '正在加载...' : '没有更多数据~' }}
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
}

.viewport {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

// tabs
.tabs {
  display: flex;
  justify-content: space-around;
  line-height: 60rpx;
  margin: 0 10rpx;
  background-color: #fff;
  box-shadow: 0 4rpx 6rpx rgba(240, 240, 240, 0.6);
  position: relative;
  z-index: 9;

  .titem {
    flex: 1;
    text-align: center;
    padding: 20rpx;
    font-size: 28rpx;
    color: #262626;
  }

  .cursor {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 20%;
    height: 6rpx;
    padding: 0 50rpx;
    background-color: #27ba9b;
    /* 过渡效果 */
    transition: all 0.4s;
  }
}

// swiper
.swiper {
  background-color: #f7f7f8;
}

// 订单列表
.orders {
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
